    //
    //  EJSShoppingCartViewController.m
    //  EnjoyShoppingStreet
    //
    //  Created by lifayu on 2017/12/13.
    //  Copyright © 2017年 lifayu. All rights reserved.
    //

#import "EJSShoppingCartViewController.h"
#import "EJSShopCartGoodsCell.h"
#import "EJSVipCell.h"
#import "EJSSettleViewController.h"
#import "EJSShoppingCartListRequest.h"
#import "EJSUpdateShopCartRequest.h"
#import "EJSUpgradeVipViewController.h"
#import "JSONKit.h"
#import "EJSGetCartsRebateRequest.h"
#import "EJSShoppingCartGoodsModel.h"

@interface EJSShoppingCartViewController ()<UITableViewDelegate,UITableViewDataSource,EJSShopCartGoodsCellDelegate>{
    BOOL _allSelectState;
}
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (weak, nonatomic) IBOutlet UIButton *selectAllButton;
@property (weak, nonatomic) IBOutlet UILabel *rebateLabel;
@property (weak, nonatomic) IBOutlet UILabel *totalLabel;
@property (weak, nonatomic) IBOutlet UIButton *settleButton;

@property (strong, nonatomic) NSMutableArray *rebatesArray;

@property (strong, nonatomic) EJSShoppingCartListModel *shoppingCartListModel;

@end

@implementation EJSShoppingCartViewController

- (void)viewDidLoad {
    [super viewDidLoad];
        // Do any additional setup after loading the view.
    self.navigationItem.title = @"购物车";
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
        // Dispose of any resources that can be recreated.
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self getCartList];
}


- (void)configOwnViews
{
    [self.tableView registerNib:[UINib nibWithNibName:@"EJSShopCartGoodsCell" bundle:nil] forCellReuseIdentifier:@"EJSShopCartGoodsCell"];
    [self.tableView registerNib:[UINib nibWithNibName:@"EJSVipCell" bundle:nil] forCellReuseIdentifier:@"EJSVipCell"];
    [self.settleButton setBackgroundImage:[UIImage fly_imageWithColor:AppMainColor] forState:UIControlStateNormal];
    [self.settleButton setBackgroundImage:[UIImage fly_imageWithColor:[UIColor lightGrayColor]] forState:UIControlStateDisabled];
    self.settleButton.enabled = NO;
    self.tableView.tableHeaderView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 0, 0.01)];
    self.tableView.tableFooterView = [UIView new];

//    [self.tabBarItem setBadgeColor:AppMainColor];
}
#pragma mark - loadData
- (void)getCartList{
    FlyWeakSelf
    EJSShoppingCartListRequest *req = [EJSShoppingCartListRequest new];
    [req asyncRequestWithsuccessHandler:^(BaseResponse *response) {
        weakSelf.shoppingCartListModel = response.data;
        [weakSelf updateUI];
    } failHandler:^(BaseResponse *response) {
        [[HUDHelper sharedInstance] tipMessage: response.message];
    }];
}

- (void)updateUI{

    [self updateShopCartRebates];//更新VIP获取返利的基数

    if(self.shoppingCartListModel.list.count > 0){
        [self hideNoDataView];
    }else{
        [self showNoDataViewWithText:@"暂无购物车商品"];
    }
    self.selectAllButton.selected = self.shoppingCartListModel.wholeSelected;

    NSString *totalRebateStr = [NSString stringWithFormat:@"返利：€%.2f",self.shoppingCartListModel.selectedGoodsTotalRebate];
    NSMutableAttributedString *totalRebateAttrStr = [[NSMutableAttributedString alloc] initWithString:totalRebateStr];
    [totalRebateAttrStr addAttribute:NSForegroundColorAttributeName value:AppPriceTextColor range:NSMakeRange(3, totalRebateStr.length - 3)];
    self.rebateLabel.attributedText = totalRebateAttrStr;

    NSString *totalPriceStr = [NSString stringWithFormat:@"合计：€%.2f",self.shoppingCartListModel.selectedGoodsTotalPrice];
    NSMutableAttributedString *totalPriceAttrStr = [[NSMutableAttributedString alloc] initWithString:totalPriceStr];
    [totalPriceAttrStr addAttribute:NSForegroundColorAttributeName value:AppPriceTextColor range:NSMakeRange(3, totalPriceStr.length - 3)];
    self.totalLabel.attributedText = totalPriceAttrStr;

    if(self.shoppingCartListModel.list.count == 0){
        self.navigationItem.title = @"购物车";
        [self.tabBarItem setBadgeValue:NULL];

        [self.tabBarItem setBadgeColor: NULL];
    }else{
        self.navigationItem.title = [NSString stringWithFormat:@"购物车(%li)",self.shoppingCartListModel.list.count];
        [self.tabBarItem setBadgeValue:[NSString stringWithFormat:@"(%li)",self.shoppingCartListModel.list.count]];
    }
    self.settleButton.enabled = self.shoppingCartListModel.hasSelectedGoods;
    [self.tableView reloadData];
}

#pragma mark - Actions

- (IBAction)selectAllAction:(UIButton *)sender {
    self.shoppingCartListModel.wholeSelected = !sender.selected;
    [self updateUI];
}
- (IBAction)settleAction:(UIButton *)sender {
    EJSSettleViewController *settleVC = [[EJSSettleViewController alloc] initWithNibName:@"EJSSettleViewController" bundle:nil];
    settleVC.settleGoods = self.shoppingCartListModel.selectedGoodsList;
    [self.navigationController pushViewController:settleVC animated:YES];
}


#pragma mark TabelViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.shoppingCartListModel.list.count + 1;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if(indexPath.row == 0)
      {
        return 60;
      }
    if(indexPath.row < self.shoppingCartListModel.list.count){
        return 115;
    }
    return 130;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if(indexPath.row == 0){
        EJSVipCell *cell = [tableView dequeueReusableCellWithIdentifier:@"EJSVipCell" forIndexPath:indexPath];
        if(self.rebatesArray.count > 0){
            NSMutableArray *couponStringArray = [NSMutableArray array];
            for (EJSRebateModel *rebateModel in self.rebatesArray) {
                NSString *string = [NSString stringWithFormat:@"升级%@,可获得返利：€ %@",rebateModel.levelName,rebateModel.rebate];
                [couponStringArray addObject:string];
            }
            cell.vipLabel.text = [couponStringArray componentsJoinedByString:@"\n"];
        }else{
            cell.vipLabel.text = @"升级会员可获取返利";
        }


        cell.layer.shadowColor = UIColorFromRGB(0xF4F4F4).CGColor;//shadowColor阴影颜色
        cell.layer.shadowOffset = CGSizeMake(0,3);//shadowOffset阴影偏移,x向右偏移4，y向下偏移4，默认(0, -3),这个跟shadowRadius配合使用
        cell.layer.shadowOpacity = 0.8;//阴影透明度，默认0
        cell.layer.shadowRadius = 4;//阴影半径，默认3
        return cell;
    }else{
        EJSShopCartGoodsCell *cell = [tableView dequeueReusableCellWithIdentifier:@"EJSShopCartGoodsCell" forIndexPath:indexPath];
        EJSShoppingCartGoodsModel *cartModel = self.shoppingCartListModel.list[indexPath.row - 1];
        cell.contentView.backgroundColor = kClearColor;
        cell.backgroundColor = kClearColor;
        [cell setShoppingGoodsCartModel:cartModel];
        cell.delegate = self;
        return cell;
    }
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 0.01;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 0.01;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (indexPath.row == 0) {
        if([self userIsLogin]){
            EJSUpgradeVipViewController *upgradVipVC = [[EJSUpgradeVipViewController alloc] initWithNibName:@"EJSUpgradeVipViewController" bundle:nil];
            [self.navigationController pushViewController:upgradVipVC animated:YES];
        }
    }
}

#pragma mark - EJSShopCartGoodsCellDelegate
- (void)shopCartGoodsCell:(EJSShopCartGoodsCell *)cell selectGoods:(EJSShoppingCartGoodsModel *)model{
    model.selectState = !model.selectState;
    [self updateUI];
}

- (void)shopCartGoodsCell:(EJSShopCartGoodsCell *)cell addGoodsNum:(EJSShoppingCartGoodsModel *)model{

    NSInteger selectNum = model.num.intValue;
    model.num = @(selectNum + model.minToBuy.intValue).stringValue;
    [self updateShopCartRequest];
}
- (void)shopCartGoodsCell:(EJSShopCartGoodsCell *)cell substractGoodsNum:(EJSShoppingCartGoodsModel *)model{
    NSInteger selectNum = model.num.intValue;
    if(selectNum - 1 > 0){
        model.num = @(selectNum - 1).stringValue;
        [self updateShopCartRequest];
    }else if (selectNum - 1 == 0){
        [self shopCartGoodsCell:cell deleteGoods:model];
    }

}
- (void)shopCartGoodsCell:(EJSShopCartGoodsCell *)cell deleteGoods:(EJSShoppingCartGoodsModel *)model{
    [HUDHelper alertTitle:@"提示" message:@"是否删除购物车中的该商品" cancelButtonTitle:@"取消" confirmButtonTitle:@"确认" action:^{
        NSMutableArray *tempGoodsList = [self.shoppingCartListModel.list mutableCopy];
        [tempGoodsList removeObject:model];
        self.shoppingCartListModel.list = tempGoodsList;
        [self updateShopCartRequest];
    }];
}

- (void)updateShopCartRequest{
    NSMutableArray *datas = [NSMutableArray array];
    for (EJSShoppingCartGoodsModel *goodsModel in self.shoppingCartListModel.list) {
        EJSUpdateShopCartModel *model = [EJSUpdateShopCartModel new];
        model.cart_id = goodsModel.cartId;
        model.sku_id = goodsModel.spuId;
        model.num = goodsModel.num;
        [datas addObject:[model getJsonDictionary]];
    }

    EJSUpdateShopCartRequest *req = [EJSUpdateShopCartRequest new];
    req.data = [datas JSONString];
    [req asyncRequestWithsuccessHandler:^(BaseResponse *response) {
        [self getCartList];
    } failHandler:^(BaseResponse *response) {
        [[HUDHelper sharedInstance] tipMessage:response.message];
    }];
}

- (void)updateShopCartRebates{
    NSMutableArray *datas = [NSMutableArray array];
    for (EJSShoppingCartGoodsModel *shopCartModel in self.shoppingCartListModel.selectedGoodsList) {
        EJSUpdateShopCartModel *model = [EJSUpdateShopCartModel new];
        model.cart_id = shopCartModel.cartId;
        model.sku_id = shopCartModel.spuId;
        model.num = shopCartModel.num;
        [datas addObject:[model getJsonDictionary]];
    }
    EJSGetCartsRebateRequest *req = [EJSGetCartsRebateRequest new];
    req.data = [datas JSONString];
    req.hideLoadingView = YES;
    FlyWeakSelf
    [req asyncRequestWithsuccessHandler:^(BaseResponse *response) {
        weakSelf.rebatesArray = [[response.data vips] mutableCopy];
        [weakSelf.tableView reloadData];
    } failHandler:^(BaseResponse *response) {
        weakSelf.rebatesArray = nil;
        [weakSelf.tableView reloadData];
    }];
}

@end

